const app = getApp();
const https = require('../../utils/https');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: '',
    tel: '',
    captch: '',
    //设置验证码初始
    sendTime: '获取验证码',
    snsMsgWait: 60,
    // 所在城市初始化
    region: [],
    regionActive: '所在城市',
    // 业务专长
    expertise: [],
    expertise_name: '业务专长',
    expertise_id: 0,
    // 当前是否在职
    job: ['全职', '兼职'],
    jobActive: '兼职/全职',
    // 证书初始化
    certificate: '../../images/upload.png',
    certificates: '',
    inspector_info: '',
    act: 'add',
    telDisabled: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this,
    login_status = wx.getStorageSync('login_status');
  if (!login_status || login_status <= 0) {
    wx.showLoading({
      title: '请先进行登陆',
    })
    setTimeout(() => {
      wx.hideLoading({
        success: (res) => {
          wx.navigateTo({
            url: '/pages/grant/grant',
          })
        },
      })
    }, 1500);
  } else {
    that.getRegisterInfo();
    that.getExpertise(); //获取业务专长
  }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {


  },
  getRegisterInfo: function(){
    var that = this,
        user_id = wx.getStorageSync('user_id');
    https.post('getInspectorInfo',{user_id: user_id},false,'正在查询').then(res=>{
      if(res){
        that.setData({
          inspector_info: res,
          tel: res.tel,
          name: res.name,
          telDisabled: true,
          expertise_id: res.expertise_id,
          expertise_name: res.expertise_name,
          regionActive: res.position,
          jobActive: res.job_active,
          picsx: res.pics,
          pics: res.picsx,
          act: 'edit'
        })
      }
    })
  },
  /**
   * @xk 获取业务专长
   */
  getExpertise: function () {
    var that = this;
    https.post('getExpertise', {}, false, '正在加载').then(res => {
      that.setData({
        expertise: res
      })
    })
  },
  /**
   * @xk 提交订单
   */
  submit: function () {
    var that = this,
      name = this.data.name,
      tel = this.data.tel,
      captch = this.data.captch,
      expertise_id = this.data.expertise_id,
      expertise_name = this.data.expertise_name,
      position = this.data.regionActive,
      job_active = this.data.jobActive,
      act = this.data.act,
      newList = this.data.certificates;
    if (name == '') {
      wx.showToast({
        title: '请填写姓名',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (tel == '') {
      wx.showToast({
        title: '请填写手机号',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (captch == '') {
      wx.showToast({
        title: '请填写验证码',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (expertise_id <= 0) {
      wx.showToast({
        title: '请选择业务专长',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (position == '' || position == '所在城市') {
      wx.showToast({
        title: '请选择所在城市',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (job_active == '' || job_active == '兼职/全职') {
      wx.showToast({
        title: '请选择兼职/全职',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if(act == 'add'){
      if (newList.length > 0) {
        that.uploadPic({
          path: newList
        });
      } else {
        wx.showToast({
          title: '请上传资质证书',
          icon: 'none',
          duration: 2000
        })
        return false;
      }
    }else{
      if (newList.length > 0) {
        that.uploadPic({
          path: newList
        });
      }else{
        that.formsubimt();
      }
    }

  },

  chanageName(obj) {
    this.setData({
      name: obj.detail.value
    })
  },
  chanageTel(obj) {
    this.setData({
      tel: obj.detail.value
    })
  },
  chanageCaptch(obj) {
    this.setData({
      captch: obj.detail.value
    })
  },

  // 获取验证码
  sendCode: function () {
    var that = this,
      user_id = wx.getStorageSync('user_id'),
      act = this.data.act,
      tel = this.data.tel;
    if (user_id <= 0) {
      wx.redirectTo({
        url: '/pages/grant/grant',
      })
    }
    if (!tel || tel == '') {
      wx.showToast({
        title: '请输入正确的手机号码',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    https.post('sendInspectorCode', {
      user_id: user_id,
      tel: tel,
      act: act,
      type: 'resgister'
    }, false, '验证码获取中').then(res => {
      if (res) {
        // 60秒后重新获取验证码
        var inter = setInterval(function () {
          this.setData({
            smsFlag: true,
            sendTime: this.data.snsMsgWait + 's后重发',
            snsMsgWait: this.data.snsMsgWait - 1
          });
          if (this.data.snsMsgWait < 0) {
            clearInterval(inter)
            this.setData({
              sendTime: '获取验证码',
              snsMsgWait: 60,
              smsFlag: false
            });
          }
        }.bind(this), 1000);
      }
    })
  },
  //地址选择
  bindRegionChange: function (e) {
    this.setData({
      regionActive: e.detail.value[0] + e.detail.value[1] + e.detail.value[2]
    })
  },
  // 业务专长选择
  bindexpertiseChange: function (e) {
    this.setData({
      expertise_name: this.data.expertise[e.detail.value].name,
      expertise_id: this.data.expertise[e.detail.value].id
    })
  },
  //当前是否在职选择
  bindjobChange: function (e) {
    this.setData({
      jobActive: this.data.job[e.detail.value]
    })
  },
  // 时间选择
  bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value
    })
  },
  // 证书上传
  certificateImg: function (e) {
    var that = this
    wx.chooseImage({
      // count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        that.setData({
          certificate: tempFilePaths,
          certificates: tempFilePaths,
          picsx: '',
          pics: '',
          certificateFirst: true
        });
      }
    })
  },

  uploadPic: function (data) {
    var pics = this.data.pics ? this.data.pics : '';
    var that = this;
    var i = data.i ? data.i : 0; //当前上传的哪张图片
    var success = data.success ? data.success : 0; //上传成功的个数
    var fail = data.fail ? data.fail : 0; //上传失败的个数
    var photo_urls = this.data.photo_urls ? this.data.photo_urls : [];
    wx.uploadFile({
      url: https.url + 'upload',
      filePath: data.path[i],
      name: 'file', //这里根据自己的实际情况改
      formData: {
        id: data.id
      }, //这里是上传图片时一起上传的数据
      success: (resp) => {
        if (resp.data != '') {
          success++; //图片上传成功，图片上传成功的变量+1
          wx.showLoading({
            title: '上传第' + success + '张完成',
          })
          if (pics != '') {
            pics = pics + ',' + resp.data
          } else {
            pics = resp.data
          }
        } else {
          fail++
        }
        that.setData({
          pics: pics,
          imgs: [],
        })
        //这里可能有BUG，失败也会执行这里,所以这里应该是后台返回过来的状态码为成功时，这里的success才+1
      },
      fail: (res) => {
        fail++; //图片上传失败，图片上传失败的变量+1
      },
      complete: () => {
        i++; //这个图片执行完上传后，开始上传下一张
        if (i == data.path.length) { //当图片传完时，停止调用
          wx.hideLoading();
          wx.showToast({
            title: '上传完成',
            icon: 'success',
            duration: 1000
          });
          setTimeout(function () {
            that.formsubimt();
          }, 1000);

        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadPic(data);
        }
      }
    });
  },


  formsubimt: function () {
    var that = this,
      name = this.data.name,
      tel = this.data.tel,
      id = this.data.inspector_info.id,
      captch = this.data.captch,
      expertise_id = this.data.expertise_id,
      expertise_name = this.data.expertise_name,
      position = this.data.regionActive,
      job_active = this.data.jobActive,
      act = this.data.act,
      user_id = wx.getStorageSync('user_id'),
      pics = this.data.pics;
    https.post('saveInspector', {
      name: name,
      tel: tel,
      captch: captch,
      user_id: user_id,
      act: act,
      id: id,
      expertise_id: expertise_id,
      expertise_name: expertise_name,
      position: position,
      job_active: job_active,
      pics: pics
    }, true, '正在注册').then(res => {
      wx.redirectTo({
        url: '/pages/register_result/register_result',
      })
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onShow();
  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var timestamp = Date.parse(new Date()),
      app_name = wx.getStorageSync('app_name'),
      app_logo = wx.getStorageSync('app_logo'),
      user_id = wx.getStorageSync('user_id'),
      url = '/pages/home/home',
      timestr = timestamp / 1000;
    url += '?timestr=' + timestr;
    if (user_id > 0) {
      url += '&l_id=' + user_id;
    }
    return {
      title: app_name,
      path: url,
      imageUrl: app_logo
    }
  }
})
